var emailAccountFlag = false;
var passwordFlag = false;
var repeatFlag = false;
var nicknameFlag = false;
var authCodeFlag = false;

$(document).ready(function() {
	$("#emailAccount").focusout(function() {
		checkEmailAccount();
	});

	$("#password").focusout(function() {
		checkPassword();
	});

	$("#repeat").focusout(function() {
		checkRepeat();
	});

	$("#nickname").focusout(function() {
		checkNickname();
	});

	$("#authCode").focusout(function() {
		checkAuthCode();
	});
});

function checkEmailAccount() {
	var emailAccount = $("#emailAccount").val();
	if (!validateEmailAccount(emailAccount)) {
		$("#emailAccount").val("");
		emailAccountFlag = false;
	} else {
		$.ajax({
			url : 'http://www.txazo.com/json/isEmailAccountExists.jsps',
			type : 'post',
			data : {
				'emailAccount' : emailAccount
			},
			dataType : 'json',
			success : function(data) {
				if (data.flag == 1) {
					emailAccountFlag = true;
				} else {
					$("#emailAccount").val("");
				}
			}
		});
	}
}

function checkPassword() {
	var password = $("#password").val();
	if (!validatePassword(password)) {
		$("#password").val("");
		passwordFlag = false;
	} else {
		passwordFlag = true;
	}
}

function checkRepeat() {
	var repeat = $("#repeat").val();
	if (!validatePassword(repeat)) {
		$("#repeat").val("");
		repeatFlag = false;
	} else if (repeat != $("#password").val()) {
		repeatFlag = false;
	} else {
		repeatFlag = true;
	}
}

function checkNickname() {
	var nickname = $("#nickname").val();
	if (!validateNickname(nickname)) {
		$("#nickname").val("");
		nicknameFlag = false;
	} else {
		nicknameFlag = true;
	}
}

function checkAuthCode() {
	var authCode = $("#authCode").val();
	if (isNull(authCode)) {
		authCodeFlag = false;
	} else {
		$.ajax({
			url : 'http://www.txazo.com/json/checkAuthCode.jsps',
			type : 'post',
			data : {
				'authCode' : authCode
			},
			dataType : 'json',
			success : function(data) {
				if (data.flag == 1) {
					authCodeFlag = true;
				} else {
					$("#authCode").val("");
				}
			}
		});
	}
}

function checkValue() {
	return emailAccountFlag && passwordFlag && repeatFlag && nicknameFlag
			&& authCodeFlag;
}

function validateEmailAccount(emailAccount) {
	var pattern = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
	return pattern.test(emailAccount);
}

function validatePassword(password) {
	var pattern = /^[a-zA-Z]\w{5,17}$/;
	return pattern.test(password);
}

function validateNickname(nickname) {
	var pattern1 = /^[a-zA-Z]\w{5,17}$/;
	var pattern2 = /^[\u4e00-\u9fa5]{3,9}$/;
	return pattern1.test(nickname) || pattern2.test(nickname);
}

function isNull(obj) {
	if (obj == null || obj == "") {
		return true;
	} else {
		return false;
	}
}